package com.ukao.pad.ui.collectMoney;


import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.pad.R;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.BalanceBean;
import com.ukao.pad.bean.PayInfoBean;
import com.ukao.pad.dialog.QuiltSweepDialogFragment;
import com.ukao.pad.eventbus.PayEvent;
import com.ukao.pad.listener.OnConfirmClickListener;
import com.ukao.pad.presenter.QuiltSweepPesenter;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.KeyBoardUtil;
import com.ukao.pad.utils.T;
import com.ukao.pad.view.QuiltSweepView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.Unbinder;


import static com.ukao.pad.eventbus.PayEvent.Message.PAY_SUCCEED;


public class AlipayWeChatFragment extends MvpFragment<QuiltSweepPesenter> implements QuiltSweepView{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.main_sweep)
    RadioButton mainSweep;
    @BindView(R.id.by_sweep)
    RadioButton bySweep;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.left_layout)
    ImageView leftLayout;
    @BindView(R.id.right_layout)
    ImageView rightLayout;
    @BindView(R.id.payment_code)
    EditText etInputCode;
    @BindView(R.id.main_sweep_layout)
    LinearLayout mainSweepLayout;
    @BindView(R.id.layout)
    LinearLayout layout;
    Unbinder unbinder;

    private PayInfoBean mPayInfo;
    private boolean isWeChat;
    private boolean isRequested;  //是否已请求过二维码
    private BalanceBean mBalance;
    private boolean isVisible;
    private Handler mHandler = new Handler();
    private QuiltSweepDialogFragment mQuiltSweep;

    public static AlipayWeChatFragment newInstance(PayInfoBean mPayInfo ,boolean  isWeChat) {
        AlipayWeChatFragment fragment = new AlipayWeChatFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1,mPayInfo);
        args.putBoolean(ARG_PARAM2, isWeChat);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isWeChat= getArguments().getBoolean(ARG_PARAM2);
            mPayInfo=getArguments().getParcelable(ARG_PARAM1);
        }
    }

    @Override
    protected QuiltSweepPesenter createPresenter() {
        return new QuiltSweepPesenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_alipay_we_chat, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }

    @Override
    protected void initView() {

    }


    @Override
    protected void initListener() {
        super.initListener();
        etInputCode.setOnEditorActionListener(mOnEditorActionListener);

    }

    TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER || actionId == EditorInfo.IME_ACTION_DONE) {
                String strPaymentCode = getText(etInputCode);
                if (!strPaymentCode.isEmpty()) {
                        etInputCode.setText("");
                        mvpPresenter.wxMicroPay(mPayInfo.getOrderId(),String.valueOf(mPayInfo.getPayBalance()), strPaymentCode, isWeChat, mPayInfo.isUseUPay(), mPayInfo.getCpnRelId());
                }

            }
            etInputCode.setText("");
            KeyBoardUtil.hideInputmethod(etInputCode);
            return false;
        }
    };



    @OnCheckedChanged({R.id.main_sweep, R.id.by_sweep})
    public void OnCheckedChanged(CompoundButton view, boolean check) {
        if (check) {
            switch (view.getId()) {
                case R.id.main_sweep:  //主扫
                    showSelectBackground(true);
                    break;
                case R.id.by_sweep:  //被扫
                    showSelectBackground(false);
                    if (!isRequested) {
                        if (mPayInfo != null){
                            mvpPresenter.wxUnifiedOrder(mPayInfo.getOrderId(), String.valueOf(mPayInfo.getPayBalance()),isWeChat,mPayInfo.isUseUPay(),mPayInfo.getCpnRelId());
                        }
                    } else {
                        showQuiltSweepDialog();
                    }
                    break;
            }
        }

    }

    /**
     * 显示选择的背景
     * @param isMainScan
     */
    public void showSelectBackground(boolean isMainScan) {
        if (isMainScan) {
            mainSweepLayout.setVisibility(View.VISIBLE);
            leftLayout.setVisibility(View.VISIBLE);
            rightLayout.setVisibility(View.INVISIBLE);
        } else {
            mainSweepLayout.setVisibility(View.GONE);
            leftLayout.setVisibility(View.INVISIBLE);
            rightLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 加载二维码数据成功
     * 显示付款二维码
     * @param mBalance
     */
    @Override
    public void loadQRCodeData(BalanceBean mBalance) {
        this.mBalance=mBalance;
        isRequested = true;
        showQuiltSweepDialog();
        postDelayedQuery();
    }

    /**
     * 显示被扫对话框
     */
    public void showQuiltSweepDialog() {
        String codeUrl = mBalance.getCodeUrl();
        int    shouldPrice= mPayInfo.getShouldPrice();
        mQuiltSweep= QuiltSweepDialogFragment.newInstance(codeUrl,shouldPrice,isWeChat);
        mQuiltSweep.setOnConfirmClickListener(mOnDialogSureClick);
        mQuiltSweep.show(getChildFragmentManager(), QuiltSweepDialogFragment.class.getName());
    }


    private OnConfirmClickListener mOnDialogSureClick = new OnConfirmClickListener() {
        @Override
        public void onChildItemClick(int id, Object msg) {
            if (CheckUtils.isNull(mainSweep)) return;
                 mainSweep.setChecked(true);
                mvpPresenter.unlockOrder(mPayInfo.getOrderId());

        }

    };


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible = true;
        postDelayedQuery();

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        KeyBoardUtil.hideInputmethod(etInputCode);
        isVisible = false;
        removeCallbacks();
    }

    public void postDelayedQuery() {
        if (isRequested && isVisible)
            mHandler.postDelayed(mRunnable, 1500);
    }

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mvpPresenter.queryStatusBySeq(mBalance.getSeq());
        }
    };

    public void removeCallbacks() {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void loadFail(String msg) {
        T.show(msg);
    }

    @Override
    public void queryStatusData(BalanceBean mBalance) {
        switch (mBalance.getStatus()) {
            case -1:
                mQuiltSweep.dismiss();
                removeCallbacks();
                T.show("交易失败");
                break;
            case 0: /*status -1.交易失败 0.交易中 1.交易成功*/

                removeCallbacks();
                postDelayedQuery();
                break;
            case 1:
                mQuiltSweep.dismiss();
                removeCallbacks();
                PayEvent.postNoData(PAY_SUCCEED);

                break;


        }
    }

    @Override
    public void unlockOrderData() {
        isRequested = false;
    }

    @Override
    public void unlockOrderFail() {
        isRequested = false;
    }

    @Override
    public void loadPayData(String msg) {
        dismissProgressDialog();
        PayEvent.postNoData(PAY_SUCCEED);
    }

    @Override
    public void scanPayMicroFail(String msg) {
        T.show(msg);
        mainSweep.setChecked(true);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        removeCallbacks();
    }


}
